<?php


namespace common\components;


use common\components\oss\OSS;
use common\models\c2\entity\EntityAttachmentImage;
use cza\base\models\statics\ImageSize;
use yii\base\Exception;
use yii\helpers\FileHelper;
use yii\helpers\Html;

class AttachmentBehavior extends \cza\base\modules\Attachments\behaviors\AttachmentBehavior
{
    /**
     * @param $filePath string
     * @param $owner
     * @return bool|File
     * @throws Exception
     * @throws \yii\base\InvalidConfigException
     */
    public function attachFile($filePath, $attribute, $extras = [])
    {
        $owner = $this->owner;
        if (empty($owner->id)) {
            throw new Exception('Parent model must have ID when you attaching a file');
        }
        if (!\file_exists($filePath)) {
            throw new Exception("File {$filePath} not exists");
        }

        $fileHash = md5(microtime(true) . $filePath);
        $fileType = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $newFileName = "{$fileHash}.{$fileType}";

        $fileDirPath = $this->getModule()->getFileDirPath($fileHash, $owner);
        $newFilePath = $fileDirPath . DIRECTORY_SEPARATOR . $newFileName;

        if (!copy($filePath, $newFilePath)) {
            throw new Exception("Cannot copy file! {$filePath}  to {$newFilePath}");
        }
        /** @var EntityAttachmentImage $file */
        $file = new $this->attributesDefinition[$attribute]['class'];
        if (isset($this->attributesDefinition[$attribute]['enableVersions'])) {
            $file->setEnableVersions($this->attributesDefinition[$attribute]['enableVersions']);
        }

        $file->loadDefaultValues();
        $file->setAttributes([
            'name' => pathinfo($filePath, PATHINFO_FILENAME),
            'entity_id' => $owner->id,
            'entity_class' => $this->getEntityClass(),
            'entity_attribute' => $attribute,
            'hash' => $fileHash,
            'size' => filesize($filePath),
            'content' => isset($extras['content']) ? $extras['content'] : "",
            'extension' => $fileType,
            'mime_type' => FileHelper::getMimeType($filePath),
            'logic_path' => $this->getModule()->getFileLogicPath($fileHash, $owner),
        ]);

        if ($file->save()) {

            $filename = $file->getHashFileName();
            /** @var OSS $oss */
            $oss = \Yii::$app->get('oss');
            $oss->upload($file->getLogicPath() . $filename, $file->getOriginalStorePath());

            @\unlink($filePath);
            return $file;
        } else {
            \Yii::info($file->errors);
            return false;
        }
    }

    public function getInitialPreviewUrls($attribute, $imageFormat = ImageSize::THUMBNAIL) {
        $initialPreview = [];

        foreach ($this->getFiles($attribute) as $file) {
            $initialPreview[] = $file->getUrlByFormat($imageFormat);
        }

        return $initialPreview;
    }

}